import java.util.*;

/**
 * @author LKQ
 * @date 2022/4/9 18:53
 * @description 栈，栈底元素为当前已经遍历过的元素中「最后一个没有被匹配的右括号的下标」，初始时放置-1进去
 */
public class Solution2 {
    public static void main(String[] args) {

    }
    public int longestValidParentheses(String s) {
        int maxans = 0;
        Deque<Integer> stack = new LinkedList<Integer>();
        stack.push(-1);
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                stack.push(i);
            } else {
                stack.pop();
                if (stack.isEmpty()) {
                    stack.push(i);
                } else {
                    maxans = Math.max(maxans, i - stack.peek());
                }
            }
        }
        return maxans;
    }
}
